<template>
    <section name="map">
        <div ref="MapMouthNode" style="width:100%;min-height:400px;" :style="{height:height}"></div>
    </section>
</template>

<script>
import jsonp from 'jsonp'
import maps from 'qqmap'

export default {
    data () {
        return {
            map: null,
            markersArray: [],
            visible: false,
            searchService: null,
            geocoder: null,
            searchResult: [],
            result: null,
            markersData: null,
            oldcityName: '',
            latLng: null,
            keyed: 'NGIBZ-HQEKS-YFCOG-6FU4M-DGFKZ-AYBEF'
        }
    },
    props: {
        isclick: {
            type: Boolean,
            default: true
        },
        height: {
            type: String,
            default: 'calc(100vh - 46px)'
        },
        searchVal: {
            type: String,
            default: ''
        },
        cityName: {
            type: String,
            default: ''
        },
        getData: {
            required: false,
            type: Object
        },
        searchClickData: {
            required: false,
            type: Object
        },
        markers: {
            required: false,
            type: Array,
            default: []
        }
    },
    watch: {
        searchVal (keyword) {
            this.searchService.search(keyword);
            console.log(1);
        },
        cityName (cityName) {
            console.log(cityName + "-==============")
            console.log(this.oldcityName + "-==============")
            if (this.oldcityName != cityName) {
                this.searchService.setLocation(cityName);
                this.oldcityName = cityName
                this.geocoder.getLocation(cityName);
            }
        },
        getData (data) {
            this.markersData = data;
        },
        searchClickData (latLng) {
            this.addMarkers(latLng)
        },
        markers (v) {
            if (v) {
                this.addmarkersArray(v)
            }
        }
    },
    created () {
    },
    mounted () {
        //判断是否支持 获取本地位置
        if (navigator.geolocation) {
            // navigator.geolocation.getCurrentPosition(function (position) {
            //     console.log(position);
            // });
        }
        else {
            //this.$message.error('浏览器不支持定位.');
        }
        this.$nextTick(e => {
            this.init();
        })
        console.log('mounted')
    },
    activated () {
        console.log('activated')
    },
    deactivated () {
        //缓存地图
        console.log('deactivated')
    },
    methods: {
        initw (myLatlng, d) {
            let _this = this;
            const myOptions = {
                zoom: 13,
                center: myLatlng ? myLatlng : new qq.maps.LatLng(1, 1),
                zoomControl: false,
                mapTypeControl: false,
                bounds_changed: function (d) {
                    var b = _this.map.getBounds()
                    if (b) {

                        console.log("地图的可视范围为：" + b);
                        var southwest = b.lat.minY + ',' + b.lng.minX;
                        var northeast = b.lat.maxY + ',' + b.lng.maxX;
                        _this.$emit('boundsChanged', southwest, northeast);
                    }
                }
            }
            this.map = new qq.maps.Map(this.$refs.MapMouthNode, myOptions)

            if (myLatlng == null) {
                //获取城市列表接口设置中心点
                const citylocation = new qq.maps.CityService({
                    complete: function (result) {
                        console.log(result.detail.latLng)
                        _this.oldcityName = result.detail.name
                        _this.$emit('changeCityName', result.detail.name);
                        _this.map.setCenter(result.detail.latLng);
                        _this.addMarkers(result.detail.latLng);
                        //生成地址检索
                        _this.initSearch();

                    }
                });
                //调用searchLocalCity();方法  根据用户IP查询城市信息。
                citylocation.searchLocalCity();
            } else {
                _this.oldcityName = d.city
                _this.$emit('changeCityName', d.city);
                _this.map.setCenter(myLatlng);
                _this.addMarkers(myLatlng);
                //生成地址检索
                _this.initSearch();
            }
            const infoWin = new qq.maps.InfoWindow({
                map: this.map
            })
            if (this.isclick) {
                //点击地图事件
                this.listener = new qq.maps.event.addListener(this.map, 'click', function (event) {
                    _this.addMarkers(event.latLng);
                });
            }
        },
        init () {
            let _this = this;
            maps.init(this.keyed, () => {
                _this.Comm.position(function (d) {
                    let myLatlng = null
                    if (d && d.code == 1) {
                        var url = 'https://apis.map.qq.com/ws/coord/v1/translate?locations=' + d.lat + ',' + d.lng + '&type=3&key=' + _this.keyed + '&output=jsonp'
                        jsonp(url, { timeout: 2000 }, (err, data) => {
                            if (data && data.status == 0) {
                                // _this.$dialog.alert({
                                //     title: '提示',
                                //     message: JSON.stringify(data),
                                //     confirmButtonText: '我知道了'
                                // })

                                myLatlng = new qq.maps.LatLng(data.locations[0].lat, data.locations[0].lng);
                                _this.initw(myLatlng, d)
                            } else if (err) {
                                _this.initw(myLatlng, d)
                                console.log(err.message);
                            }
                        });

                    } else {
                        _this.initw(myLatlng, d)
                    }
                })

                this.geocoder = new qq.maps.Geocoder({
                    complete: function (result) {
                        console.log('result', result);
                        var addressComponents = result.detail.addressComponents
                        _this.$api.common.regionCity({ keyword: addressComponents.city, key: _this.keyed }).then(d => {
                            if (d.code == 1 && d.data) {
                                if (d.data.message == 'query ok' && d.data.result && d.data.result.length > 0) {
                                    _this.result = {
                                        address: addressComponents.province + addressComponents.city + addressComponents.district + addressComponents.street + addressComponents.town + addressComponents.streetNumber,
                                        detail: addressComponents,
                                        location: result.detail.location,
                                        citycode: d.data.result[0][0].id
                                    }
                                    if (_this.isclick) {
                                        var label = new qq.maps.Label({
                                            offset: new qq.maps.Size(0, 55),
                                            position: result.detail.location,
                                            style: { width: '150px', 'white-space': 'normal' },
                                            map: _this.map,
                                            content: _this.result.address
                                        });
                                        _this.markersArray.push(label);
                                    }

                                    _this.map.setCenter(result.detail.location);
                                    _this.$emit('clickBack', _this.result);
                                }
                            } else {
                                _this.$notify({ type: 'danger', message: d.msg })
                            }
                        }).catch((e) => {

                        })
                    }
                });
            })
        },
        initSearch () {
            // 设置Poi检索服务，用于本地检索、周边检索
            this.searchService = new qq.maps.SearchService({
                // 设置搜索范围为cityName
                location: this.oldcityName,
                // 设置动扩大检索区域。默认值true，会自动检索指定城市以外区域。
                // autoExtend: true,
                // 设置展现查询结构到infoDIV上
                //panel: this.$refs.searchPopover,
                // 检索成功的回调函数
                complete: r => {
                    console.log('r', r)
                    if (r.detail) {
                        if (r.detail.totalNum > 0) {
                            this.searchResult = r.detail.pois

                        } else {
                            this.searchResult = [];
                        }
                    } else {
                        this.searchResult = [];
                    }
                    this.$emit('searchResult', this.searchResult);
                },
                // 若服务请求失败，则运行以下函数
                error: (e) => {
                    this.searchResult = [];
                    this.$emit('searchResult', this.searchResult);
                    //this.$message.error(e);
                }
            })
        },
        addmarkersArray (v) {
            if (this.latLng) {
                if (this.markersArray && this.markersArray.length > 0 && this.markersArray[0].id == -1) {

                } else {
                    this.addMarkers(this.latLng, true)
                }
            }
            v.forEach(e => {
                if (this.markersArray.findIndex(z => z.id == e.id) < 0) {
                    const latLng = new qq.maps.LatLng(e.latitude, e.longitude);
                    var decoration = e.content ? new qq.maps.MarkerDecoration(e.content, new qq.maps.Point(0, 30)) : null;
                    var marker = new qq.maps.Marker({
                        id: e.id,
                        position: latLng,
                        icon: new qq.maps.MarkerImage(e.iconPath, new qq.maps.Size(e.width, 100), new qq.maps.Point(0, 0), new qq.maps.Point(e.width / 2, e.height), new qq.maps.Size(e.width, e.height)),
                        map: this.map,
                        decoration: decoration
                    });
                    this.markersArray.push(marker);
                }
            })
        },
        addMarkers (latLng, iscenter) {
            try {
                this.latLng = latLng;
                this.clearOverlays();
                //this.map.setCenter(latLng);
                //创建标记
                console.log(latLng)
                var marker = new qq.maps.Marker({
                    id: -1,
                    position: latLng,
                    icon: new qq.maps.MarkerImage("https://hygm.oss-cn-shanghai.aliyuncs.com/img/2020/5/8/1588935260491.png", new qq.maps.Size(50, 50), new qq.maps.Point(0, 0), new qq.maps.Point(25, 50), new qq.maps.Size(50, 50)),
                    map: this.map
                });
                this.markersArray.unshift(marker);
                if (!iscenter) {
                    this.geocoder.getAddress(latLng);
                }
            } catch (e) {

            }
        },
        //清除覆盖层
        clearOverlays () {
            if (this.markersArray) {
                this.markersArray.forEach(e => {
                    e.setMap(null);
                })
                this.markersArray = [];
            }
        },
        city () {
        }
    }
}
</script>

<style>
section[name="map"] a,
section[name="map"] span {
  visibility: hidden;
}
</style>
